<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button @click="save()" :disabled="!canSave">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            v-model:data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            @handleEvent="changeHandle"
          >
            <template v-slot:form-deptName>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择部门"
                v-model="formInfo.data.deptName"
              >
                <template #append>
                  <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </PageForm>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!formInfo.data.deptId" @click="addProduct()"
                >添加产品</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除产品</el-button
              >
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <!-- 表格 -->
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                v-model:query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                              :min="0"
                              :max="99999999"
                            />
                          </el-form-item>
                          <div class="PageTable-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="scope.row.unitConvertCoefficient - 1"
                            />
                          </el-form-item>
                          <div class="PageTable-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="PageTable-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
              </PageTable>
            </el-form>
          </div>

          <NewSelectProduct
            v-if="productInfo.visible"
            v-model:showDialog="productInfo.visible"
            v-model:query="productInfo.query.queryMap"
            :api="productInfo.api"
            :query-params="productInfo.query.queryParams"
            :tableKey="productInfo.tableKey"
            :showPrice="$permission('purchTemplate:price')"
            @callback="selectProduct"
          />

          <SelectDept
            v-if="selectDeptInfo.visible"
            v-model:showDialog="selectDeptInfo.visible"
            :checkBox="false"
            :highlightRow="true"
            :saveEmpty="true"
            v-model:query="selectDeptInfo.query"
            @callback="selectDeptCallback"
          />

          <!--选择供应商-->
          <SelectSupplier
            v-if="selectProductSupplier.visible"
            v-model:show-dialog="selectProductSupplier.visible"
            :check-box="false"
            :highlightRow="true"
            :api="selectProductSupplier.api"
            v-model:query="selectProductSupplier.query"
            @callback="selectSupplierCallback"
          />
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="purchTemplateModify">
import {
  createPurchTemplate,
  updatePurchTemplate,
  getPurchTemplateDetailAll,
  getPurchTemplateById,
  getPurchTemplateDetailCustomizeList,
  getDeptProduct,
  purchOrderById,
  purchOrdersDetailCustomizeListAll,
} from '@/api/purch.js'
import { getCustomizeSetting } from '@/api/customize'
import { getSupplierProductPage } from '@/api/core'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const store = useStore()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: () => {
      return ''
    },
  },
  purchTemplateId: {
    type: [String, Number],
  },
  purchOrderId: {
    type: [String, Number],
  },
})
const systemConfig = ref(store.state.permission.systemConfig)
const formRefs = ref([])
const formInfo = ref({
  ref: null,
  data: {
    templateType: 0,
    deptName: store.state.user.userInfo.dept
      ? store.state.user.userInfo.dept.name
      : '',
    deptId: store.state.user.userInfo.dept
      ? store.state.user.userInfo.dept.id
      : '',
    ownAllProduct: store.state.user.userInfo.dept
      ? store.state.user.userInfo.dept.ownAllProduct
      : '',
  },
  fieldList: [
    { label: '模板名称', value: 'name', type: 'input' },
    { label: '部门', value: 'deptName', type: 'slot' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
    deptName: [{ required: true, message: '请选择部门', trigger: 'change' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    // sort: "create_time desc"
    customizeUserVO: {},
    queryMap: {
      purchTemplateId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.purchTemplateId,
      },
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
const filterInfoPurch = ref({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      deptId: null,
    },
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    {
      value: 'qty',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      // {
      //   label: '切换供应商',
      //   event: changeSupplier,
      //   show: true,
      // },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
//选择产品相关
const productInfo = ref({
  api: getDeptProduct,
  visible: false,
  tableKey:
    'purchTemplateModifyProduct-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      deptId: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      status: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      putShelfStatus: {
        asTbName: 'core_product_new',
        columnName: 'put_shelf_status',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      isConsignment: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      deptId: null,
    },
  },
})
const selectProductSupplier = ref({
  visible: false,
  index: '',
  api: getSupplierProductPage,
  query: {
    id: '',
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: 1,
    deptId: '',
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    tableInfo.value.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price == null ? 0 : row.price)
      )
      row.productionDate =
        row.productionDate === '1900-01-01' ? undefined : row.productionDate
    })
  },
  { deep: true }
)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.data.length
})

function changeHandle(e, val) {
  if (e === 'isConsignBusiness') {
    tableInfo.value.data = []
    if (val == 1) {
      formInfo.value.data.isConsignBusinessValue = '是'
    } else if (val == 0) {
      formInfo.value.data.isConsignBusinessValue = '否'
    }
  }
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function addProduct() {
  productInfo.value.query.queryMap.id.value = null
  //查询部门产品ids
  if (!formInfo.value.data.deptId) {
    proxy
      .$confirm('请选择部门', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        openDeptWindow()
      })
    return
  }
  productInfo.value.query.queryParams.deptId = formInfo.value.data.deptId
  if (tableInfo.value.data.length) {
    productInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.productId)
      .toString()
  }
  productInfo.value.query.queryMap.isConsignment.value =
    formInfo.value.data.isConsignBusiness
  productInfo.value.visible = true
}
//选择供应商
function changeSupplier(row, index) {
  selectProductSupplier.value.visible = true
  selectProductSupplier.value.query.productId = row.productId
  selectProductSupplier.value.query.supplierIdNotIn = row.supplierId
  selectProductSupplier.value.index = index
}
//供应商返回
function selectSupplierCallback(data) {
  let index = selectProductSupplier.value.index
  if (
    data &&
    Object.keys(data).length &&
    tableInfo.value.data[index].supplierId !== data.supplierId
  ) {
    tableInfo.value.data[index] = {
      ...tableInfo.value.data[index],
      supplierId: data.supplierId,
      supplierName: data.supplierName,
      price: data.price,
    }
  }
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
//选择产品
function selectProduct(rows) {
  if (rows) {
    const data = rows.map(function (item) {
      return {
        ...item,
        productId: item.id,
        largeUnitQty: item.largeUnitQty || 0,
        smallUnitQty: item.smallUnitQty || 0,
        defaultSupplierName: item.supplierName,
        defaultSupplierCode: item.supplierCode,
        defaultSupplierPrice: item.price,
      }
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.value.data['deptName'] = row.name
    formInfo.value.data['deptId'] = row.id
    formInfo.value.data['ownAllProduct'] = row.ownAllProduct
    productInfo.value.query.queryParams.deptId = row.id
    tableInfo.value.data = []
  } else {
    formInfo.value.data['deptName'] = ''
    formInfo.value.data['deptId'] = ''
    formInfo.value.data['ownAllProduct'] = ''
    productInfo.value.query.queryParams.deptId = ''
    tableInfo.value.data = []
  }
}
function openDeptWindow() {
  selectDeptInfo.value.visible = true
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.value.data
      .filter((item) => item.productId)
      .map((item) => {
        return {
          productId: item.productId,
          qty: item.qty,
          calcQty: item.calcQty,
          sumAmount: item.sumAmount,
          supplierId: item.supplierId,
          price: item.price,
        }
      })
    const data = formInfo.value.data
    if (!details.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    data.details = details
    data.details.forEach((item) => {
      item.isConsignBusiness = formInfo.value.data.isConsignBusiness
      item.isConsignBusinessValue = formInfo.value.data.isConsignBusinessValue
    })
    const api = data.id ? updatePurchTemplate : createPurchTemplate
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
function getMain() {
  getPurchTemplateById(props.purchTemplateId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })
  filterInfo.value.query.queryMap.purchTemplateId.value = props.purchTemplateId
  getList()
}
function getPurchOrderDetail() {
  purchOrderById(props.purchOrderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data.deptId = resp.data.deptId
      formInfo.value.data.deptName = resp.data.deptName
      productInfo.value.query.queryParams.deptId = resp.data.deptId
      let param = {
        tableKey:
          'purchOrderDetail-com.slip.spd.entity.vo.purch.PurchOrderDetailVO',
      }
      getCustomizeSetting(param).then((res) => {
        if (res && res.success) {
          let data = res.data
          filterInfoPurch.value.query.customizeUserVO = data
          filterInfoPurch.value.query.queryMap.orderId.value =
            props.purchOrderId
          purchOrdersDetailCustomizeListAll(filterInfoPurch.value.query).then(
            (resp) => {
              if (resp && resp.success) {
                const data = resp.data.map(function (item) {
                  return {
                    ...item,
                    defaultSupplierName: item.supplierName,
                    defaultSupplierCode: item.supplierCode,
                    defaultSupplierPrice: item.price,
                  }
                })
                tableInfo.value.data = data.concat(tableInfo.value.data)
              }
            }
          )
        }
      })
    }
  })
}
function getList() {
  getPurchTemplateDetailCustomizeList(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
//获取申购单明细
function getPurchTemplateDetails(purchTemplateId) {
  const params = {
    purchTemplateId,
  }
  getPurchTemplateDetailAll(params).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
//获取申购单主表
function getPurchTemplate(purchTemplateId) {
  getPurchTemplateById(purchTemplateId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'purchTemplateAddAndModifyDetail-com.slip.spd.entity.vo.purch.PurchTemplateDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      if (props.purchTemplateId) {
        getMain()
      }
      if (props.purchOrderId) {
        getPurchOrderDetail()
      }
    }
  })
}

let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    showUnitName: true, //是否显示单位
    showQty: true, //大小单位数量输入单元格是否显示计算后的qty
    isCalculation: false, //是否计算得到大小单位最大输入值
    largeUnitQty: 'largeUnitQty',
    smallUnitQty: 'smallUnitQty',
    largeRules: [
      { validator: proxy.$validate.positive, trigger: 'blur' },
      { validator: proxy.$validate.positive, trigger: 'change' },
    ],
    smallRules: [
      { validator: proxy.$validate.positive, trigger: 'blur' },
      { validator: proxy.$validate.positive, trigger: 'change' },
    ],
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchTemplate:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    permission: !proxy.$permission('purchTemplate:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('purchTemplate:price'),
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
if (!props.purchTemplateId) {
  formInfo.value.fieldList = formInfo.value.fieldList.filter(
    (item) => item.value !== 'id'
  )
}

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})
</script>

<style scoped lang="scss">
:deep(.table-scroll-hidden) > .el-table {
  overflow-y: hidden;
}
</style>
